<template>
  <div style="border: 1px solid #ccc;z-index: 99;">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :default-config="props.toolbarConfig"
    />
    <Editor
      v-bind="$attrs"
      style="height: 500px;"
      :default-config="editorConfig"
      @on-created="handleCreated"
    />
  </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// import { i18nChangeLanguage } from '@wangeditor/editor'
import useUserStore from '@/store/user'
import useThemeStore from '@/store/theme'

const userStore = useUserStore()
const themeStore = useThemeStore()

defineOptions({
  name: 'AppEditor'
})

const props = defineProps({
  toolbarConfig: {
    type: Object,
    default: () => ({})
  },
  editorConfig: {
    type: Object,
    default: () => ({})
  }
})

// 多语言
// i18nAddResources(lang.value, (locale.value.ql as Record<string, any>)?.editor || {})
// i18nChangeLanguage(userStore.locale)

// 实例
const editorRef = shallowRef()

const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      server: themeStore.upload,
      headers: {
        XSTOKEN: userStore.token
      },
      fieldName: 'file',
      customInsert (res, insertFn) {
        console.log(res)
        insertFn(res.url)
      },
      onError (file, err, res) {
        ElMessage({
          message: '文件上传有误',
          type: 'warning'
        })
      }

    },
    uploadVideo: {
      server: themeStore.upload,
      headers: {
        XSTOKEN: userStore.token
      },
      fieldName: 'file',
      customInsert (res, insertFn) {
        insertFn(res.url)
      },
      onError (file, err, res) {
        ElMessage({
          message: '文件上传有误',
          type: 'warning'
        })
      }
    }
  },
  ...props.editorConfig
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

</script>

<style lang="scss">
</style>
